﻿var ae_ready = {};
var $ae = new function() {
    this.applyAwesomeStyles = function() {
        $(".ae-lookup-openbtn").empty().prepend('<span class="ui-icon ui-icon-newwin"></span>');
        $(".ae-lookup-clearbtn").empty().prepend('<span class="ui-icon ui-icon-gear"></span>');
        $ae.mybutton(".ae-lookup-openbtn");
        $ae.mybutton(".ae-lookup-clearbtn");
    }

    this.mybutton = function(sel) {
        $(sel).unbind('mousedown mouseup mouseleave')
        .hover(function() { $(this).addClass("ui-state-hover"); },
	            function() { $(this).removeClass("ui-state-hover"); })
        .bind({ 'mousedown mouseup': function() { $(this).toggleClass('ui-state-active'); } })
        .addClass("ui-state-default").addClass("ui-corner-all")
        .bind('mouseleave', function() { $(this).removeClass('ui-state-active') });
    }

    this.interactive = function(o) {
        $(o + ' input:text').keyup(function(e) {
            if ($ae.isKeyChange(e.which)) {
                $(o).submit();
            }

        });
        $(o + ' input[type="hidden"], ' + o + ' .ae-array').change(function() {
            $(o).submit();
        });
    }

    this.isKeyChange = function(w) {
        if (w < 9 || w > 45 && w < 91 || w > 93 && w < 112 || w > 185 || w == 32) return true;
        return false;
    }

    this.fullscreen = function(o) {
        $(window).bind("resize", function() { $(o).dialog("option", { height: $(window).height() - 50, width: $(window).width() - 50 }).trigger('dialogresize'); });
    }

    loadRadioList = function(o, url) {
        $.post(url,
        { key: $('#' + o).val() },

        function(d) {
            $("#" + o + "list").empty();
            if (typeof (d) == 'object')
                $.each(d, function(i, j) {
                    var sel = "";
                    if (j.Selected == true) sel = "checked = 'checked'";
                    $("#" + o + "list").append("<li><input type='radio' " + sel + " value='" + j.Value + "' name='" + o + "' id='" + o + i + "'/><label for='" + o + i + "' >" + j.Text + "</label></li>");
                });
        });
    }

    this.radioList = function(o, url) {
        loadRadioList(o, url);
        $('#' + o + 'list input').live('change',
        function() {
            $('#' + o).val($('#' + o + 'list input:checked').val()).change();
        }
        );
    }

    this.ajaxDropdown = function(o, p, url, keys, values, pkeys, pvals) {
        this.loadAjaxDropdown(o, p, url, false, keys, values, pkeys, pvals);

        $("#" + o + "dropdown").keyup(function() { $(this).change(); })
    .change(function() {
        $('#' + o).val($('#' + o + 'dropdown').val()).trigger('change');
    });

        if (p) $('#' + p).change(function() { $ae.loadAjaxDropdown(o, p, url, true, keys, values, pkeys, pvals); });
        $.each(keys, function(i, k) {
            $('#' + k).change(function() { $ae.loadAjaxDropdown(o, p, url, true, keys, values, pkeys, pvals); });
        });
        //if keys foreach key change same 
    }

    this.loadAjaxDropdown = function(o, p, url, c, keys, values, pkeys, pvals) {
        if (c) $('#' + o).val(null);

        var data = new Array();
        data.push({ name: "key", value: $('#' + o).val() });
        if (p) data.push({ name: "parent", value: $('#' + p).val() });

        $.each(pkeys, function(i, k) {
            data.push({ name: k, value: pvals[i] });
        });

        $.each(keys, function(i, k) {
            if ($('#' + k).attr('name')) {
                data.push({ name: values[i], value: $('#' + k).val() });
            } else {
                $('#' + k).find('input').each(function() {
                    data.push({ name: values[i], value: $(this).val() });
                });
            }
        });


        sload($('#' + o + "dropdown"), true);

        $.get(url, data,
        function(d) {
            $("#" + o + "dropdown").empty();
            if (typeof (d.d) == 'object')
                $.each(d.d, function(i, j) {
                    var sel = "";
                    if (j.Selected == true) sel = "selected = 'selected'";
                    $("#" + o + "dropdown").append("<option " + sel + " value=\"" + j.Value + "\">" + j.Text + "</option>");
                });
            $('#' + o).val($('#' + o + 'dropdown').val());
            //if (c) 
            $("#" + o + "dropdown").trigger('change');
            ae_ready[o] = true;
            eload($('#' + o + "dropdown"), true);
        });
    }



    this.autocomplete = function(o, k, p, u, mr, delay, minLen, keys, values) {
        $('#' + o).autocomplete({
            delay: delay,
            minLength: minLen,
            source: function(request, response) {
                var data = new Array();
                data.push({ name: 'searchText', value: request.term });
                data.push({ name: 'maxResults', value: mr });

                if (p) data.push({ name: 'parent', value: $('#' + p).val() });

                $.each(keys, function(i, k) {
                    if ($('#' + k).attr('name')) {
                        data.push({ name: values[i], value: $('#' + k).val() });
                    } else {
                        $('#' + k).find('input').each(function(index) {
                            data.push({ name: values[i], value: $(this).val() });
                        });
                    }
                });

                $.ajax({
                    url: u, type: "POST", dataType: "json",
                    data: data,
                    success: function(d) { response($.map(d, function(o) { return { label: o.Text, value: o.Text, id: o.Id} })); }
                });
            }
        });

        $('#' + o).bind("autocompleteselect", function(e, ui) {
            $('#' + k).val(ui.item ? ui.item.id : null).trigger('change');
            $('#' + o).trigger('change');
        });

        $('#' + o).keyup(function(e) { if (e.which != '13') $("#" + k).val(null).trigger('change'); });
    }



    this.popup = function(o, w, h, title, modal, pos, res, btns, fulls) {
        var draggable = true;
        if (fulls) { res = false; modal = true; }
        if (modal || fulls) draggable = false;
        $("#" + o).dialog({
            show: "fade",
            draggable: draggable,
            width: fulls ? $(window).width() - 50 : w,
            height: fulls ? $(window).height() - 50 : h,
            title: title,
            modal: modal,
            position: pos,
            resizable: res,
            buttons: btns,
            autoOpen: false,
            close: function() { $("#" + o).find('*').remove(); $(this).remove(); }
        });

        if (modal || fulls) $("#" + o).dialog("option", { dialogClass: 'ae-fixed' });
        if (fulls) this.fullscreen("#" + o);
    }

    loadLookupDisplay = function(o, url) {
        if ($('#' + o).val())
            $.get(url, { id: $('#' + o).val() }, function(d) { $('#' + o + 'display').val(d.d); });
    }

    this.lookup = function(o, urlGet, urlSearch) {
        loadLookupDisplay(o, urlGet);
        var div = o + 'd';
        var btn = o + 'btn';
        $('#' + btn).click(function() {
            if ($('#' + div).length != 0) return;

            $('<div id="' + div + '"><div class="ae-search"></div><ul class="ae-result"></ul></div>').dialog({ close: function() { $(this).remove(); } });
            $('<input type="text" name="search"/>').appendTo('#' + div + ' .ae-search');
            $('<input type="button" value="search"/>')
                .click(function() {
                    $.get(urlSearch, { search: $('#' + div + ' .ae-search [name="search"]').val() }, function(d) {
                        $('#' + div + ' .ae-result').empty();
                        if (typeof (d.d) == 'object')
                            $.each(d.d, function(i, j) {

                                $('#' + div + ' .ae-result').append("<li data-val='" + j.Id + "'>" + j.Content + " </li>");
                            });

                        $('#' + div + ' .ae-result li').click(function() {
                            $('#' + o).val($(this).data('val'));
                            loadLookupDisplay(o, urlGet);
                            $('#' + div).remove();
                        });
                    });
                })
                .appendTo('#' + div + ' .ae-search').click();
        });
    }



    //    this.multilookupLoadDisplay = function(o, url) {
    //        var ids = $("#" + o + " input").map(function() { return $(this).attr("value"); }).get();
    //        $("#ld" + o).html('');
    //        if (ids.length != 0) {
    //            
    //            $.post(url, $.param({ selected: ids }, true),
    //                function(d) {
    //                    if (d && d != null) {
    //                        $.each(d, function() { $("#ld" + o).append('<li>' + this.Text + '</li>') });
    //                    }
    //                });
    //        }
    //    }

    this.lookupChoose = function(o, url, sel) {
        $('#' + o).val('');
        $('#' + o).val($('#' + o + 'ls .' + sel).attr("data-value")).change();
        this.loadLookupDisplay(o, url);
        $("#lp" + o).dialog('close');
    }

    this.multiLookupChoose = function(o, loadUrl, prop) {
        $("#" + o).empty();
        $.each($("#" + o + "se li").map(function() { return $(this).attr("data-value"); }).get(), function() {
            $("#" + o).append($("<input type='hidden' name='" + prop + "' \>").attr("value", this));
        });
        $("#" + o).change();
        this.multilookupLoadDisplay(o, loadUrl);
        $("#lp" + o).dialog('close');
    }

    this.lookupClear = function(o) {
        $("#lc" + o).click(function() {
            $("#" + o).val("").change();
            $("#ld" + o).val("");
        });
    }

    this.multiLookupClear = function(o) {
        $("#lc" + o).click(function() {
            $("#" + o + ",#ld" + o).empty();
            $("#" + o).change();
        });
    }

    this.confirm = function(o, f, h, w, yes, no) {
        $("#dialog-confirm-" + o).dialog({
            show: "fade",
            hide: "fade",
            resizable: false,
            height: h,
            width: w,
            modal: true,
            autoOpen: false,
            dialogClass: 'ae-fixed'
        })
    .dialog("option", "buttons", [
    {
        text: yes,
        click: function() { $(this).dialog("close"); f.submit(); }
    },
    {
        text: no,
        click: function() { $(this).dialog("close"); }
    },
    ]);

        $("." + o).live('click', function() {
            f = $(this).closest('form');
            $("#dialog-confirm-" + o).dialog('open');
            return false;
        });
    }

    this.lookupPopupOpenClick = function(o, lck, url, paging, multi, datak, datav, park, parv) {
        $("#lpo" + o).click(function(e) {
            e.preventDefault();
            if (lck != null) return;
            lck = true;
            var data = [{ name: 'prop', value: o}];
            data.push({ name: 'paging', value: paging });
            data.push({ name: 'multi', value: multi });

            for (var i in datak) data.push({ name: 'datak', value: datak[i] });
            for (var i in datav) data.push({ name: 'datav', value: datav[i] });
            for (var i in park) data.push({ name: 'park', value: park[i] });
            for (var i in parv) data.push({ name: 'parv', value: parv[i] });

            $.get(url, $.param(data), function(d) {
                $("#lp" + o).html(d).dialog('open'); lck = null;
            });
        });
    }

    this.takevals = function(a, b, w) {
        $.each(a, function(i, v) {
            var e = $('#' + v);
            var t = e.attr('name') ? e : e.find('input');
            t.clone().removeAttr('id').attr('name', b[i]).appendTo('#' + w);
        });
    }

    this.multilookupGetSels = function(div) {
        return JSON.stringify($('#' + div + ' .ae-lookup-selectedlist li').map(function() { return $(this).data('val'); }).get());
    }

    this.multilookupAdd = function(o, id) {
        o.prependTo('#' + id + 'popup .ae-lookup-selectedlist ul');
    }

    this.multilookupRemove = function(o, id) {
        o.prependTo('#' + id + 'popup .ae-lookup-searchlist ul');
    }

    this.outerH = function(s) {
        var sel = $(s);
        return parseInt(sel.css('margin-top').replace("px", "")) +
            parseInt(sel.css('margin-bottom').replace("px", "")) +
                parseInt(sel.css('padding-top').replace("px", "")) +
                    parseInt(sel.css('padding-bottom').replace("px", ""));

    }

    this.multilookupLay = function(div) {
        var av = $("#" + div).height() - ($('#' + div + " .ae-search:first").outerHeight()
            + $ae.outerH('#' + div + ' .ae-lookup-searchlist:first')
                + $ae.outerH('#' + div + ' .ae-lookup-selectedlist')
                    + 10);
        $('#' + div + ' .ae-lookup-list').css('height', (av * 0.5) + 'px');
    }

    this.multilookupLoadDisplay = function(id, url) {
        var dispId = id + "Display";
        var v = $('#' + id).val();
        if (v) {
            sload($('#' + dispId).parent());
            $.get(url, { keys: v }, function(d) {
                $('#' + dispId).empty();
                if (typeof (d.d) == 'object')
                    $.each(d.d, function(ii, j) {
                        $('#' + dispId).append('<li data-val="' + j.Id + '">' + j.Content + '</li>');
                    });
                eload($('#' + dispId).parent());
            });
        }
    }

    sload = function(o, d) {

        o.before("<div class='ae-loading'><span></span></div>");
        if (d) o.attr('disabled', 'disabled'); else o.hide();
    }

    eload = function(o, d) {
        if (d)
            o.removeAttr('disabled');
        else
            o.show();

        o.prev().remove();
    }

    this.multilookup = function(o) {
        $('#' + o.id).change(function() { $ae.multilookupLoadDisplay(o.id, o.getMultipleUrl); }).change();

        $('#' + o.id + 'Open').click(function(e) {
            e.preventDefault();
            var div = o.id + 'popup';
            if ($('#' + div).length != 0) return;

            $('<div id="' + div + '"><div class="ae-search"></div><div class="ae-lookup-list ae-lookup-searchlist"><ul></ul></div><div class="ae-lookup-list ae-lookup-selectedlist" ><ul></ul></div></div>').hide().appendTo('body');

            $ae.popup(div, 400, 300, '', true, 'center', false, {
                "Ok": function() {
                    $('#' + o.id).val($ae.multilookupGetSels(div)).change();
                    $(this).dialog('close');
                },
                "Cancel": function() { $(this).dialog('close'); }
            }, o.fulls);


            $('#' + div).dialog('open');



            $('<input type="button" value="search" id="' + o.id + 'sbtn"/>')
                .click(function() {
                    var darr = new Array();
                    darr.push({ name: "search", value: $('#' + div + ' .ae-search [name="search"]').val() });
                    darr.push({ name: "selected", value: $ae.multilookupGetSels(div) });
                    for (var i in o.data.keys) darr.push({ name: o.data.keys[i], value: $('#' + o.data.vals[i]).val() });

                    sload($('#' + div + ' .ae-lookup-searchlist ul'));
                    $.get(o.searchUrl, darr, function(d) {
                        $('#' + div + ' .ae-lookup-searchlist ul').empty();

                        if (typeof (d.d) == 'object') {
                            $.each(d.d, function(ii, j) {
                                $('#' + div + ' .ae-lookup-searchlist ul').append("<li class='ae-lookup-item' data-val='" + j.Id + "'><button class='ae-lookup-mbtn'><span></span></button>" + j.Content + " </li>");
                            });
                        }
                        eload($('#' + div + ' .ae-lookup-searchlist ul'));
                    });
                })
                .appendTo('#' + div + ' .ae-search');

            $('<input type="text" name="search"/>').prependTo('#' + div + ' .ae-search')
                .keyup(function(ee) { if (ee.which == '13') $('#' + o.id + 'sbtn').click(); });

            sload($('#' + div + ' .ae-lookup-selectedlist ul'));
            $.get(o.selectedUrl, { selected: $('#' + o.id).val() }, function(d) {
                if (typeof (d.d) == 'object' && d.d != null) {
                    $.each(d.d, function(i, j) {
                        $('#' + div + ' .ae-lookup-selectedlist ul').append("<li class='ae-lookup-item' data-val='" + j.Id + "'><button class='ae-lookup-mbtn'><span></span></button>" + j.Content + " </li>");
                    });
                }
                eload($('#' + div + ' .ae-lookup-selectedlist ul'));
                $('#' + o.id + 'sbtn').click();
            });

            $('#' + div).bind('dialogresize', function() { $ae.multilookupLay(div); });
            $ae.multilookupLay(div);
        });

        $('.ae-lookup-searchlist .ae-lookup-mbtn').live('click', function() {
            $ae.multilookupAdd($(this).closest('.ae-lookup-item'), o.id);
        });
        $('.ae-lookup-selectedlist .ae-lookup-mbtn').live('click', function() {
            $ae.multilookupRemove($(this).closest('.ae-lookup-item'), o.id);
        });
    }
};

$(function() {
    $(".ae-pagination-current").addClass('ui-state-highlight');
    $ae.mybutton(".ae-pagination a");
    $ae.applyAwesomeStyles();
    $("body").ajaxComplete($ae.applyAwesomeStyles);
});
